"""
仪表盘相关API路由
"""

from datetime import datetime, timedelta
from typing import Any

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import func, desc
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select

from app.database.session import get_db
from app.models import Visitor, AuditLog
from app.routes.auth import get_current_user

router = APIRouter(tags=["dashboard"])


@router.get("/stats", response_model=dict[str, int])
async def get_dashboard_stats(
    db: AsyncSession = Depends(get_db),
    current_user: dict[str, Any] = Depends(get_current_user)
):
    """
    获取仪表盘统计数据
    """
    try:
        # 获取今日访客数量
        today = datetime.now().date()
        visitors_result = await db.execute(
            select(func.count(Visitor.id))
            .where(func.date(Visitor.created_at) == today)
        )
        total_visitors = visitors_result.scalar_one_or_none() or 0
        
        # 模拟任务数据
        today_tasks = 20
        completed_tasks = 15
        pending_tasks = 5
        
        return {
            "totalVisitors": total_visitors,
            "todayTasks": today_tasks,
            "completedTasks": completed_tasks,
            "pendingTasks": pending_tasks
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取统计数据失败: {str(e)}")


@router.get("/tasks/recent", response_model=list[dict[str, str]])
async def get_recent_tasks(
    db: AsyncSession = Depends(get_db),
    current_user: dict[str, Any] = Depends(get_current_user),
    limit: int = 5
):
    """
    获取最近的任务记录
    """
    try:
        # 获取最近的审计日志作为任务记录
        result = await db.execute(
            select(
                AuditLog.id,
                func.concat(AuditLog.operation_type, " - ", AuditLog.operation_target).label("title"),
                func.IF(AuditLog.success, "completed", "pending").label("status"),
                AuditLog.operation_time
            )
            .order_by(desc(AuditLog.operation_time))
            .limit(limit)
        )
        
        tasks: list[dict[str, str]] = []
        for row in result:
            tasks.append({
                "id": f"T{row.id:03d}",
                "title": row.title,
                "status": row.status,
                "createTime": row.operation_time.strftime("%Y-%m-%d %H:%M")
            })
        
        # 如果没有足够的审计日志，补充一些模拟任务
        if len(tasks) < limit:
            mock_tasks: list[dict[str, str]] = [
                {"id": f"T{len(tasks) + i + 1:03d}", "title": "访客登记检查", "status": "completed", "createTime": (datetime.now() - timedelta(hours=i)).strftime("%Y-%m-%d %H:%M")}
                for i in range(limit - len(tasks))
            ]
            tasks.extend(mock_tasks)
        
        return tasks[:limit]
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取任务记录失败: {str(e)}")


@router.get("/visitors/stats/weekly", response_model=list[dict[str, Any]])
async def get_weekly_visitors_stats(
    db: AsyncSession = Depends(get_db),
    current_user: dict[str, Any] = Depends(get_current_user)
):
    """
    获取近7天的访客统计数据
    """
    try:
        # 生成近7天的日期
        stats: list[dict[str, Any]] = []
        for i in range(6, -1, -1):
            date = datetime.now() - timedelta(days=i)
            date_str = date.strftime("%m/%d")
            
            # 查询当天的访客数量
            result = await db.execute(
                select(func.count(Visitor.id))
                .where(func.date(Visitor.created_at) == date.date())
            )
            count = result.scalar_one_or_none() or 0
            
            # 如果没有数据，使用随机数填充
            if count == 0:
                count = 30 + i * 2  # 递增的模拟数据
            
            stats.append({
                "date": date_str,
                "count": count
            })
        
        return stats
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取访客统计数据失败: {str(e)}")


@router.get("/tasks/completion", response_model=list[dict[str, Any]])
async def get_tasks_completion_stats(
    db: AsyncSession = Depends(get_db),
    current_user: dict[str, Any] = Depends(get_current_user)
):
    """
    获取任务完成率数据
    """
    try:
        # 查询成功和失败的审计日志数量
        success_result = await db.execute(
            select(func.count(AuditLog.id)).where(AuditLog.success == True)
        )
        success_count = success_result.scalar_one_or_none() or 0
        
        pending_result = await db.execute(
            select(func.count(AuditLog.id)).where(AuditLog.success == False)
        )
        pending_count = pending_result.scalar_one_or_none() or 0
        
        # 如果没有数据，使用默认值
        if success_count == 0 and pending_count == 0:
            success_count = 75
            pending_count = 25
        
        return [
            {"value": success_count, "name": "已完成"},
            {"value": pending_count, "name": "待处理"}
        ]
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取任务完成率数据失败: {str(e)}")